﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace iTool.ClusterComponent
{
    public class HttpRequestStatisticsService : iToolServiceBase, IHttpRequestStatisticsService
    {
        private ConcurrentDictionary<string, long> HttpRequestCounter { get; set; }

        public HttpRequestStatisticsService()
        {
            this.HttpRequestCounter = new ConcurrentDictionary<string, long>();
        }

        public override Task OnActivateAsync()
        {
            base.RegisterTimer(x => this.CreateRequest(), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
            return base.OnActivateAsync();
        }

        public async Task RequestAsync(RequestInfo clientInfo)
        {
            var key = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
            if (this.HttpRequestCounter.ContainsKey(key))
            {
                this.HttpRequestCounter[key] += 1;
            }
            else
            {
                this.HttpRequestCounter.TryAdd(key,1);
            }

            await Task.CompletedTask;
        }

        public async Task<Dictionary<string, long>> GetRequestStatisticsAsync()
        {
            return await Task.FromResult(this.HttpRequestCounter.ToDictionary(x => x.Key, x => x.Value));
        }

        private async Task CreateRequest()
        {
            string key = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
            this.HttpRequestCounter.GetOrAdd(key, 0);

            while (this.HttpRequestCounter.Count > 100)
            {
                key = this.HttpRequestCounter.OrderBy(item => item.Key).First().Key;
                this.HttpRequestCounter.TryRemove(key, out _);
            }

            await Task.CompletedTask;
        }
    }
}
